<?php

namespace app\controller\Api\V1\Client;

use app\helper\GetProductInfo;
use app\model\GameVersionRelevance;
use app\request\Version;
use Exception;
use support\Request;
use support\Response;

class VersionController
{

    protected GetProductInfo $getProductInfoRe;


    public function __construct()
    {
        $this->getProductInfoRe = GetProductInfo::getInstance();
    }


    /**
     * 获取游戏版本下载链接
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function Download(Request $request): Response
    {

        $validate = new Version;

        if (!$validate->scene('download')->check($request->all())) {
            throw new Exception($validate->getError(), 500);
        }

        if (!empty($request->input('mch_id'))) {
            $merchantInfo = $this->getProductInfoRe->GetMerchantPlatform();
            $product = $merchantInfo['ulid'];
            $user = $request->input('mch_id');
        } elseif (!empty($request->input('open_id'))) {
            $developerInfo = $this->getProductInfoRe->GetDeveloperPlatform();
            $product = $developerInfo['ulid'];
            $user = $request->input('open_id');
        } else {
            throw new Exception('非法请求', 500);
        }

        $info = GameVersionRelevance::query()->has('VersionBind')->where('product', $product)
            ->where('user', $user)->where('game', $request->input('game_id'))->latest()->first();

        if (!$info) {
            throw new Exception('版本不存在', 500);
        }

        return jsonRe([
            'url' => $info->VersionBind->url,
        ]);

    }

}